const mysql = require('mysql');
const options = require('../app-config/mysqlConf.json')

function getProjectData() {
	const connection = mysql.createConnection({
		"host": "192.168.1.2",
		"user": "root",
		"port": 3306,
		"password": "atmd@dd_2014",
		"database": "apis_db",
		"charset": "utf8_general_ci"
	});
	connection.connect();
	let SQL = 'SELECT project_data FROM tb_api_detail WHERE project_id = 1;'
	console.log('SQL', SQL)
	return new Promise((resolve, reject) => {
		console.log('xxxxxxxxxxxxxxxxx')
		connection.query(SQL, (error, results, fields) => {
			// console.log('error', error)
			// console.log('results', results)
			if (error) {
				console.log('error', error)
				return reject(error);
			}
			return resolve(results && results[0].project_data || results);
		});
	})
}

function insertProjectData(data) {
	const connection = mysql.createConnection({
		"host": "192.168.1.2",
		"user": "root",
		"port": 3306,
		"password": "atmd@dd_2014",
		"database": "apis_db_dev",
		"charset": "utf8_general_ci"
	});
	connection.connect();
	let SQL = `INSERT INTO tb_api_detail VALUES(1, '${data}')`
	return new Promise((resolve, reject) => {
		connection.query(SQL, (error, results, fields) => {
			if (error) {
				return reject(error);
			}
			return resolve(results);
		});
	})
}

async function parseProjectData() {
	let result = await getProjectData()
	result = result.replace(/^["'`]|["'`]$/g, '')
	result = result.replace(/[\r\n\t]/g, '')
	try {
		result = JSON.parse(result)
	} catch (e) {
		console.log('e', e)
		result = new Function(`return ${result};`)()
	}
	// console.log(result)
	let modules = result.modules
	let modulesArr = Object.values(modules)
	let projectData = {
		name: result.name,
		project_name: result.name,
		version: result.version,
		create_user: result.create_user,
		testServerUrl: result.testServerUrl,
		tree: {},
		apis: {},
	};
	for (let i = 0; i < modulesArr.length; i++) {
		let module = modulesArr[i]
		projectData.tree[module.id] = {
			id: module.id,
			text: module.text,
			attributes: {
				type: 'module',
				parentNodeId: '',
				prevNodeId: module.attributes.prevNodeId,
				nextNodeId: module.attributes.nextNodeId,
				firstChildId: module.attributes.firstChildId,
			},
		}
		let apiArr = Object.values(module.apis)
		for (let j = 0; j < apiArr.length; j++) {
			let api = apiArr[j]
			let requestParameterList = api.attributes.requestParameterList
			let responseParameterList = api.attributes.responseParameterList
			if (typeof requestParameterList == 'string') {
				requestParameterList = JSON.parse(requestParameterList)
			}
			if (typeof responseParameterList == 'string') {
				responseParameterList = JSON.parse(responseParameterList)
			}
			projectData.tree[api.id] = {
				id: api.id,
				text: api.text,
				attributes: {
					type: 'api',
					parentNodeId: module.id,
					prevNodeId: api.attributes.prevNodeId,
					nextNodeId: api.attributes.nextNodeId,
					firstChildId: '',
				},
			}
			let apiObj = {
				id: api.id,
				name: api.text,
				intro: api.attributes.intro,
				method: api.attributes.method,
				path: api.attributes.path,
				contentType: api.attributes.contentType,
				requestParameterList,
				responseParameterList,
			}
			projectData.apis[api.id] = apiObj
		}
	}

	// console.log('projectData', projectData)

	let str = JSON.stringify(JSON.stringify(projectData))

	let resultInsert = await insertProjectData(str)
	console.log('projectData', typeof str)
	console.log('resultInsert', resultInsert)

}

parseProjectData()

// tree = {
// 	nodeId: {
// 		type: '',
// 		parentNodeId: '',
// 		nextNodeId: '',
// 		prevNodeId: '',
// 	}
// }

// let projectData = {
// 	name: params.name,
// 	project_name: params.name,
// 	version: '0.0.1',
// 	create_user: params.create_user,
// 	testServerUrl,
// 	modules: {
// 		'module-00000000': {
// 			id: "module-00000000",
// 			text: "module-默认模块1",
// 			state: 'open',
// 			attributes: {
// 				prevNodeId: '',
// 				nextNodeId: '',
// 				firstChildId: 'api-00000000',
// 			},
// 			apis: {
// 				'api-00000000': {
// 					id: "api-00000000",
// 					text: "默认接口1",
// 					attributes: {
// 						moduleId: 'module-00000000',
// 						prevNodeId: '',
// 						nextNodeId: '',
// 						intro: "",
// 						method: "GET",
// 						path: "",
// 						contentType: "application/x-www-form-urlencoded",
// 						requestParameterList: [],
// 						responseParameterList: []
// 					},
// 				},
// 			},
// 		},
// 	}
// };